<template>
  <view class="container">
    <!-- 右上角用户名 -->
    <view class="navbar-username" @click="goToMyPage" v-if="userInfo">
      {{ userInfo.username }}
    </view>

    <!-- 搜索框 -->
    <view class="search-container" @click="goToSearchPage">
      <view class="search-box">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input 
          class="search-input" 
          placeholder="请输入搜索内容"
          v-model="searchText"
          @confirm="handleSearch"
          disabled
        />
      </view>
    </view>

    <!-- 书籍列表区域 -->
    <view class="book-list">
      <view 
        class="book-item" 
        v-for="book in books" 
        :key="book.bookId" 
        @click="goToDetail(book.bookId)"
      >
        <image 
          class="book-cover" 
          src="/static/屏幕截图 2025-06-22 200009.png" 
          mode="aspectFill"
        />
        <view class="book-info">
          <text class="book-name">{{ book.bookName }}</text>
          <text class="book-author">作者：{{ book.author }}</text>
          <view class="book-meta">
            <text class="book-type">{{ book.bookType }}</text>
            <text class="book-score">★ {{ book.score }}</text>
          </view>
          <text class="book-intro" v-if="book.introduction">{{ book.introduction }}</text>
        </view>
      </view>
    </view>

    <!-- 空状态提示 -->
    <view v-if="books.length === 0 && !loading" class="empty-state">
      <text class="empty-text">暂无书籍数据</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const userInfo = ref(null)
const searchText = ref('')
const books = ref([])
const loading = ref(false)

// API配置
const API_BASE_URL = 'http://192.168.153.1:8080'

onMounted(() => {
  loadUserInfo()
  fetchBooks()
})

const loadUserInfo = () => {
  const savedUser = uni.getStorageSync('userInfo')
  if (savedUser) {
    userInfo.value = savedUser
    console.log('加载用户信息:', savedUser)
  }
}

const fetchBooks = async () => {
  loading.value = true
  uni.showLoading({ title: '加载中...' });
  
  try {
    const response = await new Promise((resolve, reject) => {
      uni.request({
        // 修复：使用正确的端口8080
        url: `HTTP://192.168.153.1:8080/books/getBooks`,
        method: 'GET',
        timeout: 10000, // 10秒超时
        success: (res) => {
          console.log('API响应:', res)
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(`HTTP状态码: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          console.error('请求失败:', err)
          reject(err)
        }
      });
    });
    
    console.log('获取到的书籍数据:', response)
    
    // 修复：检查响应结构并映射字段
    if (response && response.code === 200200 && response.data && response.data.books) {
      books.value = response.data.books.map(book => ({
        bookId: book.book_id,
        bookName: book.book_name,
        author: book.author,
        score: book.score,
        bookType: book.book_type,
        publisher: book.publisher,
        isbn: book.isbn,
        introduction: book.introduction
      }));
      
      console.log('映射后的书籍数据:', books.value)
      
      uni.showToast({
        title: `成功加载${books.value.length}本书籍`,
        icon: 'success',
        duration: 2000
      });
    } else {
      console.warn('响应数据格式不正确:', response)
      books.value = [];
      uni.showToast({
        title: '数据格式错误',
        icon: 'none',
        duration: 3000
      });
    }
  } catch (error) {
    console.error('获取书籍失败:', error);
    books.value = [];
    
    let errorMessage = '获取书籍失败'
    if (error.errMsg) {
      if (error.errMsg.includes('timeout')) {
        errorMessage = '请求超时，请检查网络连接'
      } else if (error.errMsg.includes('fail')) {
        errorMessage = '网络连接失败，请检查服务器地址'
      }
    }
    
    uni.showToast({
      title: errorMessage,
      icon: 'none',
      duration: 3000
    });
  } finally {
    loading.value = false
    uni.hideLoading();
  }
}

const goToDetail = (bookId) => {
  const user = uni.getStorageSync('userInfo')
  if (!user?.U_Id) {
    console.log('用户未登录，不记录浏览历史')
    uni.navigateTo({
      url: `/pages/bookdetail/bookdetail?id=${bookId}`
    })
    return
  }

  console.log('准备记录浏览历史，用户ID:', user.U_Id, '书籍ID:', bookId)
  
  // 使用回调函数方式记录浏览历史
  uni.request({
    // 修复：使用统一的API地址
    url: `HTTP://192.168.153.1:8080/history/insert`,
    method: 'POST',
    data: {
		"userId":user.U_Id,
		"bookId":bookId
	},
    timeout: 5000,
    success: (res) => {
      if (res.statusCode === 200) {
        console.log('浏览历史记录成功', res.data)
      } else {
        console.error('记录失败:', res.data)
      }
    },
    fail: (err) => {
      console.error('记录浏览历史请求失败:', err)
      // 即使记录失败也继续跳转
    },
    complete: () => {
      // 无论记录成功与否都跳转到详情页
      uni.navigateTo({
        url: `/pages/bookdetail/bookdetail?id=${bookId}`
      })
    }
  })
}

const goToMyPage = () => {
  uni.navigateTo({
    url: '/pages/my/my'
  })
}

const goToSearchPage = () => {
  uni.navigateTo({
    url: '/pages/reserch/reserch'
  })
}

const handleSearch = () => {
  if (!searchText.value.trim()) return
  uni.navigateTo({
    url: `/pages/reserch/reserch?keyword=${encodeURIComponent(searchText.value)}`
  })
}

// 刷新书籍列表
const refreshBooks = () => {
  fetchBooks()
}

// 下拉刷新
const onPullDownRefresh = () => {
  fetchBooks().finally(() => {
    uni.stopPullDownRefresh()
  })
}

// 暴露方法供外部调用
defineExpose({
  refreshBooks,
  onPullDownRefresh
})
</script>

<style>
/* 全局样式 */
page {
  background-color: #f8f8f8;
  padding-top: 20rpx;
}

.container {
  min-height: 100vh;
}

/* 导航栏用户名样式 */
.navbar-username {
  position: fixed;
  right: 30rpx;
  top: 30rpx;
  z-index: 999;
  color: #333;
  font-size: 30rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
}

.navbar-username:active {
  opacity: 0.8;
}

/* 搜索框样式 */
.search-container {
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 40rpx;
  padding: 20rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.search-box:active {
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
}

.search-input {
  flex: 1;
  margin-left: 20rpx;
  font-size: 28rpx;
  height: 40rpx;
  line-height: 40rpx;
  background-color: transparent;
  pointer-events: none;
  color: #999;
}

/* 书籍列表样式 */
.book-list {
  margin: 0 20rpx;
  padding-bottom: 40rpx;
}

.book-item {
  display: flex;
  padding: 30rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.book-item:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.book-cover {
  width: 160rpx;
  height: 220rpx;
  border-radius: 8rpx;
  margin-right: 30rpx;
  background-color: #f0f0f0;
  flex-shrink: 0;
}

.book-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 220rpx;
}

.book-name {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  word-break: break-all;
}

.book-author {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.book-meta {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  flex-wrap: wrap;
  gap: 20rpx;
}

.book-type {
  font-size: 24rpx;
  color: #fff;
  background-color: #4a90e2;
  padding: 6rpx 12rpx;
  border-radius: 20rpx;
  white-space: nowrap;
}

.book-score {
  font-size: 28rpx;
  color: #ff9900;
  font-weight: bold;
}

.book-intro {
  font-size: 26rpx;
  color: #888;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  word-break: break-all;
  flex: 1;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  text-align: center;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-top: 20rpx;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .book-item {
    padding: 20rpx;
  }
  
  .book-cover {
    width: 120rpx;
    height: 160rpx;
    margin-right: 20rpx;
  }
  
  .book-name {
    font-size: 30rpx;
  }
  
  .book-author {
    font-size: 26rpx;
  }
}
</style>